package com.example.yan_music.view.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.yan_music.R;
import com.example.yan_music.adapter.XFlowAdapter;
import com.example.yan_music.adapter.RcvSearchAdapter;
import com.example.yan_music.adapter.MainViewPagerAdapter;
import com.example.yan_music.app.Api;
import com.example.yan_music.base.fragment.BaseFragment;
import com.example.yan_music.bean.wangyi.NewSearchSong;
import com.example.yan_music.contract.ISearchContract;
import com.example.yan_music.db.table.HistoryRecord;
import com.example.yan_music.event.PlayDurationEvent;
import com.example.yan_music.event.PlayerInfoEvent;
import com.example.yan_music.event.SetThreadInterrupt;
import com.example.yan_music.event.SongCoverUriEvent;
import com.example.yan_music.listener.OnRcvClickListener;
import com.example.yan_music.presenter.ISearchPresenterImp;
import com.example.yan_music.service.PlayerService;
import com.example.yan_music.utils.KeyboardUtils;
import com.example.yan_music.utils.XDataPool;
import com.example.yan_music.utils.XLog;
import com.example.yan_music.utils.XToast;
import com.example.yan_music.view.MainActivity;
import com.example.yan_music.view.MainFragment;
import com.example.yan_music.widge.XFlowLayout;
import com.example.yan_music.widge.dialog.XDialog;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 搜索歌曲，歌手的Fragment
 * <p/>
 */
public class SearchFragment extends BaseFragment implements ISearchContract.View, XFlowAdapter.OnSearchFromHistory,
        OnRcvClickListener , RcvSearchAdapter.OnSelectItemListener , MainViewPagerAdapter.OnReplaceable {

    /**
     * 设置刷新头和尾部的文字设置，静态初始化防止内存泄漏
     */
    static {
        // 头部设置
        ClassicsHeader.REFRESH_HEADER_PULLING = "下拉免费为老板刷一哈";
        ClassicsHeader.REFRESH_HEADER_REFRESHING = "正在使劲搜索...";
        ClassicsHeader.REFRESH_HEADER_LOADING = "加载中";
        ClassicsHeader.REFRESH_HEADER_RELEASE = "老板可以松手啦";
        ClassicsHeader.REFRESH_HEADER_FINISH = "刷新完成";
        ClassicsHeader.REFRESH_HEADER_FAILED = "刷新失败";
        ClassicsHeader.REFRESH_HEADER_UPDATE = "上次更新 M-d HH:mm";
        // 尾部设置
        ClassicsFooter.REFRESH_FOOTER_PULLING = "上拉一下有更多哦";
        ClassicsFooter.REFRESH_FOOTER_RELEASE = "老板可以放手啦";
        ClassicsFooter.REFRESH_FOOTER_LOADING = "正在努力加载哦...";
        ClassicsFooter.REFRESH_FOOTER_FINISH = "♬... 加 载 完 成 啦 ...♬";
    }

    private static final String TAG = "SearchFragment";

    /**
     * 用于表示搜索第几页
     */
    private int offset = 1;

    /**
     * 当前播放位置，初始值为-1（不是0 的值都可以）的原因是防止第一次搜索呈现列表时第一项就被自动选中
     */
    private int currentPosition = -1;

    /**
     * 是否拦截物理返回键事件，t表示拦截，f表示不拦截
     */
    private boolean isHandleBackEvent = true;

    /**
     * RecyclerView子项之间的间距
     */
    private static final int ITEM_SPACE = 0;    // 设置为 0 是因为点击水波纹不满视觉效果

    private MainActivity mMainActivity;

    /**
     * 对应的 Presenter
     */
    private ISearchPresenterImp iSearchPresenterImp;

    /**
     * 控件
     */
    private EditText edt_keywords; // 搜索框
    private RecyclerView mSearchRecyclerView, mSearchHistoryRecyclerView; // 展示列表，搜索历史列表
    private TextView tv_search, tv_type; // 搜索按钮, 搜到结果数
    private ImageView img_bac; // 返回键
    private AVLoadingIndicatorView mLoadingView;  // 第三方加载框库
    private ClassicsHeader mHeader; // 头部
    private ClassicsFooter mFooter; // 尾部
    private ImageView img_delete_history; // 删除历史记录按钮
    private XDialog mXDialog; // 对话框

    /**
     * 布局
     */
    private RelativeLayout rl_loading_view, rl_history; // 加载框的布局, 历史搜索记录布局
    private SmartRefreshLayout mRefreshLayout; // 刷新布局

    /**
     * 搜索记录的流式布局+适配器+数据源
     */
    private XFlowLayout cfl_history;
    private XFlowAdapter mCflAdapter;
    private List<HistoryRecord> mHistoryList = new ArrayList<>();


    /**
     * 搜索出来的列表，RecyclerView适配器和数据源
     */
    private ArrayList<NewSearchSong.ResultBean.SongsBean> mSearchSongList = new ArrayList<>();
    private RcvSearchAdapter mSearchAdapter;
    private RcvSearchAdapter.ItemSpaceDecoration mDecoration;   // 子项装饰类

    /**
     * 播放服务相关
     */
    private PlayerService.PlayBinder mPlayBinder;
    private ServiceConnection mServiceConnection;

    public SearchFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, container, false);
        init(view);
        bindPlayService();
        modifyStatusBar(R.color.refresh_header_primary_color);
        //StatusBarUtil.setStatusBarMode(mMainActivity, true, R.color.refresh_header_primary_color);
        modifyNavigationBar(R.color.statusBarColor_main_white);
        setRcvRefresh();
        initRefreshHeaderAndFooter();
        showSearchHistory();
        Log.d(TAG, "onCreateView: " + "<历史记录数据库>中有[ " + mHistoryList.size() + " ]条数据");
        // 自动弹出软键盘
        KeyboardUtils.showKeyboard(edt_keywords);
        // 点击搜索去搜索关键字歌曲
        search();
        // 点击返回键返回上一个页面
        back();
        //点击删除历史记录按钮删除所有历史记录并将布局隐藏
        deleteHistoryRecords();
        return view;
    }

    /**
     * 删除历史记录
     */
    private void deleteHistoryRecords() {
        img_delete_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LitePal.findFirst(HistoryRecord.class) == null) {
                    // 没有记录时提示用户没有记录
                    XToast.showInfo("你还没有任何记录哦");
                } else {
                    showDeleteHistoryDialog();
                }
            }
        });
    }

    /**
     * 返回
     */
    private void back() {
        img_bac.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back(new MainFragment());
                // 隐藏软键盘
                KeyboardUtils.hideKeyboard(edt_keywords);
                modifyNavigationBar(R.color.baise);
                mMainActivity.isCoverMenuOpen();
                mMainActivity.modifyPlayrTabOneIconAndText(R.drawable.music_select, "Music", R.color.player_text_color);
            }
        });
    }

    /**
     * 搜索
     */
    private void search() {
        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 这里赋值是解决子项背景被修改，但是当前并不是正在播放的歌曲
                currentPosition = -2;
                // 将本次搜索记录添加到搜索列表中
                if (!getKeywords().equals("")) {
                    addSearchToHistoryList();
                }
                // 再次搜索前先清空之前的搜索列表，不然列表会重复的堆起来
                if (mSearchSongList != null) {
                    tv_type.setVisibility(View.GONE);
                    mSearchSongList.clear();
                    // 这里需要清除RecyclerView的 ItemDecoration，不然不断刷新的时候会导致子项之间的间距越来越大
                    mSearchRecyclerView.removeItemDecoration(mDecoration);
                }
                KeyboardUtils.hideKeyboard(edt_keywords);
                // 搜索---> P层
                iSearchPresenterImp.search(getKeywords(), 1);
            }
        });
    }

    /**
     * 初始化操作
     *
     * @param view 根view
     */
    @Override
    public void init(View view) {
        // 初始化对应的 Presenter
        iSearchPresenterImp = new ISearchPresenterImp();
        // 将 Presenter有与 对应 view 关联起来
        iSearchPresenterImp.attachView(this);

        tv_type = view.findViewById(R.id.tv_type);
        edt_keywords = view.findViewById(R.id.edt_search);
        tv_search = view.findViewById(R.id.bt_click_to_search);
        mSearchRecyclerView = view.findViewById(R.id.rcv_search_result);
        img_bac = view.findViewById(R.id.img_back);
        mLoadingView = view.findViewById(R.id.aiv_loading);
        rl_loading_view = view.findViewById(R.id.rl_loading_view);
        mRefreshLayout = view.findViewById(R.id.srl_refresh);
        cfl_history = view.findViewById(R.id.cfl_history);
        rl_history = view.findViewById(R.id.rl_history);
        img_delete_history = view.findViewById(R.id.img_delete_all);

    }

    /**
     * 获取关键字
     *
     * @return 返回关键字
     */
    @Override
    public String getKeywords() {
        return edt_keywords.getText().toString();
    }

    /**
     * 设置adapter的数据源，也就是返回来的歌曲List
     *
     * @param songList
     */
    @Override
    public void setSearchList(ArrayList<NewSearchSong.ResultBean.SongsBean> songList) {
        // 考虑到可能是从历史记录中发起的搜索，需要隐藏历史记录和软键盘
        KeyboardUtils.hideKeyboard(edt_keywords);
        mSearchSongList.addAll(songList);
        // 初始化适配器
        mSearchAdapter = new RcvSearchAdapter(mSearchSongList, getKeywords(), mMainActivity);
        mSearchAdapter.setRcvClickListener(this);
        mSearchAdapter.setOnSelectItemListener(this);
        // 设置子项的间距，这里间距是 ITEM_SPACE 这么大
        mDecoration = new RcvSearchAdapter.ItemSpaceDecoration(0,0,ITEM_SPACE, 0);
        // 设置子项进场动画
        LayoutAnimationController lac_fall_down = AnimationUtils.loadLayoutAnimation(getContext(), R.anim.layout_anim_item_fall_down);
        LayoutAnimationController lac_right_slide = AnimationUtils.loadLayoutAnimation(getContext(), R.anim.layout_anim_item_right_slipe);
        mSearchRecyclerView.setLayoutAnimation(lac_right_slide);
        // 设置布局排列方式
        mSearchRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        // 给列表子项添加分割线
        //rcv_result.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        // 设置子项之间的间距
        mSearchRecyclerView.addItemDecoration(mDecoration);
        // 设置适配器
        mSearchRecyclerView.setAdapter(mSearchAdapter);
        // 重新启动布局时调用 ViewGroup的方法
        mSearchRecyclerView.scheduleLayoutAnimation();
        tv_type.setText("单曲 (" + mSearchAdapter.getItemCount() + "首)");
        // 数据变化时刷新
        mSearchAdapter.notifyDataSetChanged();
    }

    /**
     * 将搜索字段添加到历史记录中
     */
    public void addSearchToHistoryList() {
        String keywords = getKeywords().trim();
        Log.d(TAG, "addSearchToHistoryList: " + "用户输入的关键词是: " + keywords);
        if (LitePal.where("recordName = ?", keywords).find(HistoryRecord.class).isEmpty()) {
            HistoryRecord record = new HistoryRecord();
            record.setRecordName(keywords);
            record.save();
            Log.d(TAG, "addSearchToHistoryList: " + "该记录是：" + record.getRecordName());
            mHistoryList.add(record);
        } else {
            Log.d(TAG, "addSearchToHistoryList: " + "记录[ " + keywords + " ] 已存在");
        }
    }

    /**
     * 显示搜索历史记录，当刚进入SearchFragment时，显示用户的搜索记录
     */
    public void showSearchHistory() {

        // 将<历史记录数据库>中的所有记录查询出来并添加到历史记录列表mHistoryList
        List<HistoryRecord> queryList = LitePal.findAll(HistoryRecord.class);
        Log.d(TAG, "showSearchHistory: " + "查询集大小为=" + queryList.size());
        mHistoryList.addAll(queryList);
        rl_history.setVisibility(View.VISIBLE);
        mCflAdapter = new XFlowAdapter(mHistoryList, iSearchPresenterImp, mMainActivity);
        mCflAdapter.setOnSearchFromHistory(this);
        cfl_history.setAdapter(mCflAdapter);
        cfl_history.setMaxLines(20);
        // 打印一下查到的数据
        for (int i = 0; i < queryList.size(); i++) {
            String historyRecordName = mHistoryList.get(i).getRecordName();
            Log.d(TAG, "onCreateView: " + "历史搜索数据[ " + i + " ] : " + historyRecordName);
        }
    }

    /**
     * 隐藏player视图
     *
     * @param context
     */
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "onAttach: " + TAG);
        mMainActivity = (MainActivity) context;
        //mMainActivity.hideMainPlayer();
    }

    /**
     * 销毁时显示player视图
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: " + TAG);
        //mMainActivity.showMainPlayer();
        mMainActivity.unbindService(mServiceConnection);
        iSearchPresenterImp.detachView();
    }


    /**
     * 显示加载框
     */
    @Override
    public void showLoadingDialog() {
        rl_loading_view.setVisibility(View.VISIBLE);
        mLoadingView.show();
    }

    /**
     * 隐藏加载框
     */
    @Override
    public void dismissLoadingDialog() {
        rl_loading_view.setVisibility(View.GONE);
    }

    /**
     * 搜索失败显示的对话框
     */
    @Override
    public void showSearchFieldDialog() {
        showSingleDialog(R.layout.layout_dialog_search_field);
    }

    /**
     * keywords为空弹出
     */
    @Override
    public void showKeywordsIsNullDialog() {
        showSingleDialog(R.layout.layout_dialog_words_null);
    }

    /**
     * 网络错误对话框
     */
    @Override
    public void showNetErrDialog() {
        showSingleDialog(R.layout.layout_dialog_net_err);
    }

    /**
     * 关键词为空提示用户不要刷新加载
     */
    public void showUnRefreshAndLoadMoreDialog() {
        showSingleDialog(R.layout.layout_dialog_no_refresh);
    }

    /**
     * 上拉加载，下拉刷新操作
     *
     * @param
     */
    public void setRcvRefresh() {
        // 下拉刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                Log.d(TAG, "onRefresh: " + "搜索结果列表大小=" + mSearchSongList.size());
                if (mSearchSongList.size() > 0) {
                    refreshLayout.setEnableRefresh(true);
                    iSearchPresenterImp.search(getKeywords(), 1);
                    refreshLayout.finishRefresh();
                    tv_type.setText("单曲 (" + mSearchAdapter.getItemCount() + "首)");
                } else {
                    refreshLayout.finishRefresh();
                    showUnRefreshAndLoadMoreDialog();
                }
            }
        });

        // 上拉加载
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (mSearchSongList.size() > 0) {
                    offset += 1;
                    Log.d(TAG, "onLoadMore: 第" + offset + "页");
                    iSearchPresenterImp.searchMore(getKeywords(), offset);
                    tv_type.setText("单曲 (" + mSearchAdapter.getItemCount() + "首)");
                } else {
                    refreshLayout.finishLoadMore();
                    showUnRefreshAndLoadMoreDialog();
                }
            }
        });
    }

    /**
     * 搜索更多成功
     *
     * @param songListBeans
     */
    @Override
    public void searchMoreSuccess(ArrayList<NewSearchSong.ResultBean.SongsBean> songListBeans) {
        mSearchSongList.addAll(songListBeans);
        mSearchAdapter.notifyDataSetChanged();
        tv_type.setText("单曲 (" + mSearchAdapter.getItemCount() + "首)");
        mRefreshLayout.finishLoadMore();
    }

    /**
     * 结束加载更多
     */
    @Override
    public void finishLoadMore() {
        mRefreshLayout.finishLoadMore(500);
    }

    @Override
    public void showSearchCount() {
        tv_type.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideHistoryRecord() {
        rl_history.setVisibility(View.GONE);
    }

    /**
     * 刷新头部和尾部的基础UI设置
     */
    public void initRefreshHeaderAndFooter() {
        mHeader = new ClassicsHeader(mMainActivity);
        mFooter = new ClassicsFooter(mMainActivity);
        mRefreshLayout.setRefreshHeader(mHeader);
        mRefreshLayout.setRefreshFooter(mFooter);

        // 头部相关设置
        mHeader.setPrimaryColorId(R.color.refresh_header_primary_color);
        mHeader.setAccentColorId(R.color.refresh_header_accent_color);
        mHeader.setTextSizeTime(10);

        // 尾部相关设置
        mFooter.setPrimaryColorId(R.color.refresh_footer_primary_color);
        mFooter.setAccentColorId(R.color.refresh_footer_accent_color);
    }

    /**
     * 这个方法调用的场景是：当用户点击历史记录时搜索出来的列表再刷新
     *
     * @param historyRecord
     */
    @Override
    public void onHistorySearch(final String historyRecord) {
        iSearchPresenterImp.search(historyRecord, 1);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                Log.d(TAG, "onRefresh: " + "来自历史搜索结果列表大小=" + mSearchSongList.size());
                if (mSearchSongList.size() > 0) {
                    refreshLayout.setEnableRefresh(true);
                    iSearchPresenterImp.search(historyRecord, 1);
                    refreshLayout.finishRefresh();
                    int freshCount = mSearchAdapter.getItemCount();
                    if (freshCount != 0) {
                        tv_type.setText("单曲 (" + freshCount + "首)");
                    }
                } else {
                    refreshLayout.finishRefresh();
                    showSearchFailed();
                }
            }
        });

        // 上拉加载
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (mSearchSongList.size() > 0) {
                    offset += 1;
                    Log.d(TAG, "onLoadMore: " + "offset = " + offset);
                    iSearchPresenterImp.searchMore(historyRecord, offset);
                    tv_type.setText("单曲 (" + mSearchAdapter.getItemCount() + "首)");
                } else {
                    refreshLayout.finishLoadMore();
                    showSearchFailed();
                }
            }
        });
    }

    /**
     * 搜索失败弹窗(dialog)
     */
    @Override
    public void showSearchFailed() {
        mXDialog = new XDialog.XBuilder(mMainActivity)
                .setMessage("抱歉，啥也没搜到~ ~ ~")
                .setIcon(R.drawable.ku)
                .setTitle("提示")
                .setTitleTextColor(getResources().getColor(R.color.juse))
                .setPositiveListener("好的", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mXDialog.dismiss();
                    }
                })
                .create(XDialog.XType.TIP);
        mXDialog.show();
    }

    /**
     * 删除历史记录的dialog
     */
    private void showDeleteHistoryDialog() {
        mXDialog = new XDialog.XBuilder(mMainActivity)
                .setIcon(R.drawable.jingao)
                .setPositiveTextColor(getResources().getColor(R.color.red))
                .setTitleTextColor(getResources().getColor(R.color.red))
                .setTitle("删除")
                .setMessage("确定删除所有历史记录吗？")
                .setPositiveListener("非常确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LitePal.deleteAll(HistoryRecord.class);
                        // 将记录表删除
                        LitePal.deleteAll(HistoryRecord.class);
                        Log.d(TAG, "onClick: " + "<历史数据库>被删除");
                        Log.d(TAG, "onClick: " + "删除后第一条记录为：" + LitePal.findFirst(HistoryRecord.class));
                        // 隐藏历史记录布局
                        rl_history.setVisibility(View.GONE);
                        mXDialog.dismiss();
                    }
                })
                .setNegativeListener("我再想一哈", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mXDialog.dismiss();
                    }
                })
                .create(XDialog.XType.CONFIRM);
        mXDialog.show();
    }

    /**
     * 播放搜索歌曲
     *
     * @param playUrl 歌曲播放地址
     */
    @Override
    public void playSearchSong(String playUrl) {
        // 启动播放服务
        mPlayBinder.playSong(playUrl);
    }

    /**
     * 接收歌词
     * @param lyric     歌词
     */
    @Override
    public void getSongLyric(String lyric) {
        XDataPool.getInstance().put(XDataPool.CURRENT_PLAY_SONG_LYRIC, lyric);
        XLog.d(lyric);
    }

    /**
     * 接收封面uri,通知MainActivity更新Player中的歌曲封面
     * @param url   歌曲的播放地址
     */
    @Override
    public void getSongCoverUrl(String url) {
        // 将歌曲uri事件发布出去
        EventBus.getDefault().post(new SongCoverUriEvent(url));
        XLog.d("歌曲的封面地址为：" + url);
    }

    @Override
    public void showNoMoreDataDialog() {
        mXDialog = new XDialog.XBuilder(mMainActivity)
                .setMessage("没有更多啦····")
                .setIcon(R.drawable.ku)
                .setTitle("提示")
                .setTitleTextColor(getResources().getColor(R.color.juse))
                .setPositiveListener("好的", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mXDialog.dismiss();
                    }
                })
                .create(XDialog.XType.TIP);
        mXDialog.show();
    }

    /**
     * 列表子项点击事件：点击开始播放
     *
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(View view, int position) {
        // 记录当前播放位置
        currentPosition = position;
        // 刷新Adapter重新调用onBind方法
        mSearchAdapter.notifyDataSetChanged();
        // 发送中断事件
        EventBus.getDefault().post(new SetThreadInterrupt(false));
        // 歌曲id
        int songId = mSearchSongList.get(position).getId();
        // 所属专辑id，根据这个id去请求该歌曲的封面
        int albumId = mSearchSongList.get(position).getAlbum().getId();
        // 歌曲名
        String songName = mSearchSongList.get(position).getName();
        // 歌手名
        String singerName = mSearchSongList.get(position).getArtists().get(0).getName();
        // 时长（完整的时长）
        int duration = mSearchSongList.get(position).getDuration();
        // 歌词(网络请求)
        iSearchPresenterImp.getSongLyric(songId);
        // 歌曲封面(网络请求)
        iSearchPresenterImp.getSongAlbum(albumId);

        // 发送设置SeekBar最大值事件
        EventBus.getDefault().post(new PlayDurationEvent(duration, false));

        // 获取播放地址并开始播放
        iSearchPresenterImp.getSongPlayUrl(songId, songName);

        Log.d(TAG, "onItemClick: " + "\n 点击位置index = " + position + "\n 歌曲id 为：" + songId + "\n 歌曲名：" + songName + "\n 歌手名：" + singerName);
        Log.d(TAG, "onItemClick: " + "\n 完整的歌曲播放请求地址为 " + Api.LOCAL_HOST + Api.URL_MUSIC_PLAY + "id=" + songId);

        // 通知设置Player的显示信息
        EventBus.getDefault().post(new PlayerInfoEvent(songName, singerName));
    }

    /**
     * 绑定播放服务
     */
    private void bindPlayService() {
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                XLog.d(name + "》》》》》》》》》播放服务连接成功《《《《《《《《《《");
                mPlayBinder = (PlayerService.PlayBinder) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                XLog.d(name + "服务断开连接");
            }
        };
        Intent intent = new Intent(mMainActivity, PlayerService.class);
        mMainActivity.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 当用户点击某一子项开始播放时，设置该子项的背景用来提示用户这首歌正在播放
     * @param holder    当前位置上的ViewHolder
     * @param position  当前位置
     */
    @Override
    public void convert(RcvSearchAdapter.MyHolder holder, int position) {
        if(position == currentPosition){
            holder.itemView.setBackgroundColor(getResources().getColor(R.color.item_play));
            holder.itemView.setElevation(2);
        }
    }

}